// React核心库导入
import React, { useEffect, useMemo, useState } from 'react';
// Ant Design组件库导入
import {
  Table,      // 表格组件
  Button,     // 按钮组件
  Space,      // 间距组件
  Tag,        // 标签组件
  Card,       // 卡片组件
  Input,      // 输入框组件
  Select,     // 选择器组件
  Badge,      // 徽章组件
  Tooltip,    // 工具提示组件
  message,    // 消息提示组件
  Popconfirm, // 确认对话框组件
  Dropdown,   // 下拉菜单组件
  Menu,       // 菜单组件
  Modal,      // 模态框组件
  Form,       // 表单组件
  Switch,     // 开关组件
  Descriptions, // 描述列表组件
  Progress,   // 进度条组件
  Alert,      // 警告组件
  Tabs,       // 标签页组件
  Statistic,  // 统计数值组件
  Row,        // 行组件
  Col         // 列组件
} from 'antd';
// Ant Design表格类型导入
import type { ColumnsType } from 'antd/es/table';
// Ant Design图标库导入
import { 
  PlusOutlined,        // 加号图标
  EditOutlined,        // 编辑图标
  DeleteOutlined,      // 删除图标
  ReloadOutlined,      // 刷新图标
  SearchOutlined,      // 搜索图标
  EyeOutlined,         // 查看图标
  PlayCircleOutlined,  // 播放图标
  StopOutlined,        // 停止图标
  CheckCircleOutlined, // 成功图标
  CloseCircleOutlined, // 失败图标
  SettingOutlined,     // 设置图标
  ToolOutlined,        // 工具图标
  BarChartOutlined,    // 图表图标
  WarningOutlined,     // 警告图标
  ThunderboltOutlined, // 闪电图标
  MoreOutlined,        // 更多图标
  CopyOutlined,        // 复制图标
  ExclamationCircleOutlined, // 感叹图标
  ApiOutlined,         // API图标
  DatabaseOutlined,    // 数据库图标
  CodeOutlined,        // 代码图标
  FileTextOutlined,    // 文件图标
  GlobalOutlined,      // 全球图标
  CalculatorOutlined   // 计算器图标
} from '@ant-design/icons';
// React Router路由组件导入
import { Link } from 'react-router-dom';
// 状态管理Hook导入
import { 
  useMcpTool, 
  useToolLoading, 
  useToolError, 
  useToolFilters, 
  useTools, 
  useToolStatistics, 
  useToolCategories, 
  useToolExecution,
  useToolHistory 
} from '../../contexts/McpToolContext';
// 服务层导入
import mcpToolService, {
  McpToolType,
  McpToolStatus,
  McpToolParameter,
  CreateMcpToolInput,
  UpdateMcpToolInput,
  ExecuteMcpToolInput
} from '../../services/mcpToolService';

// 解构组件
const { Search } = Input;
const { Option } = Select;
const { Group: ButtonGroup } = Button;

/**
 * MCP工具列表组件 - 工具管理主页面
 * 
 * 功能特性：
 * - 工具数据列表展示和分页
 * - 多条件搜索和过滤功能
 * - 工具状态管理操作
 * - 工具执行和连接测试
 * - 工具参数配置管理
 * - 执行历史记录查看
 * - 统计信息展示
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 2.0.0
 * @lastModified 2024-01-20
 */
const McpToolList: React.FC = () => {
  // 使用状态管理Hook
  const { state, actions } = useMcpTool();
  const loading = useToolLoading();
  const error = useToolError();
  const { filters, setFilters, resetFilters } = useToolFilters();
  const tools = useTools();
  const { statistics } = useToolStatistics();
  const categories = useToolCategories();
  const { executionResult, testResult, executeTool, testConnection, clearExecutionResult, clearTestResult } = useToolExecution();
  const { executionHistory, clearExecutionHistory } = useToolHistory();

  // 组件本地状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [executeVisible, setExecuteVisible] = useState(false);
  const [testVisible, setTestVisible] = useState(false);
  const [historyVisible, setHistoryVisible] = useState(false);
  const [selectedTool, setSelectedTool] = useState<any>(null);
  const [executeForm] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  // 工具类型图标映射
  const toolTypeIcons = {
    [McpToolType.FileSystem]: <FileTextOutlined />,
    [McpToolType.Http]: <GlobalOutlined />,
    [McpToolType.Database]: <DatabaseOutlined />,
    [McpToolType.CodeExecution]: <CodeOutlined />,
    [McpToolType.Search]: <SearchOutlined />,
    [McpToolType.Calculator]: <CalculatorOutlined />,
    [McpToolType.DataProcessing]: <BarChartOutlined />,
    [McpToolType.ApiIntegration]: <ApiOutlined />,
    [McpToolType.Custom]: <ToolOutlined />
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setFilters({ filter: value, skipCount: 0 });
  };

  // 处理类型过滤
  const handleTypeFilter = (value: McpToolType | undefined) => {
    setFilters({ toolType: value, skipCount: 0 });
  };

  // 处理状态过滤
  const handleStatusFilter = (value: McpToolStatus | undefined) => {
    setFilters({ status: value, skipCount: 0 });
  };

  // 处理激活状态过滤
  const handleActiveFilter = (value: boolean | undefined) => {
    setFilters({ isActive: value, skipCount: 0 });
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setFilters({
      skipCount: (pagination.current - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    });
  };

  // 删除工具
  const handleDelete = async (id: string) => {
    try {
      await actions.deleteTool(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 切换激活状态
  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      await actions.batchSetActive([id], isActive);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 查看工具详情
  const handleViewDetail = (tool: any) => {
    setSelectedTool(tool);
    setDetailVisible(true);
  };

  // 执行工具
  const handleExecute = (tool: any) => {
    setSelectedTool(tool);
    setExecuteVisible(true);
    executeForm.resetFields();
    clearExecutionResult();
  };

  // 执行工具操作
  const handleExecuteTool = async () => {
    try {
      const values = await executeForm.validateFields();
      await executeTool(selectedTool.id, values);
    } catch (error) {
      message.error('执行失败');
    }
  };

  // 测试连接
  const handleTestConnection = async (tool: any) => {
    setSelectedTool(tool);
    await testConnection(tool.id);
  };

  // 重置统计
  const handleResetStats = async (id: string) => {
    try {
      await actions.resetStats(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 设置工具状态
  const handleSetStatus = async (id: string, status: McpToolStatus) => {
    try {
      await actions.setStatus(id, status);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 批量操作
  const handleBatchDelete = async () => {
    try {
      await actions.batchDelete(selectedRowKeys);
      setSelectedRowKeys([]);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  const handleBatchSetActive = async (isActive: boolean) => {
    try {
      await actions.batchSetActive(selectedRowKeys, isActive);
      setSelectedRowKeys([]);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    actions.fetchTools();
    actions.fetchStatistics();
    actions.fetchCategories();
  };

  // 重置过滤器
  const handleResetFilters = () => {
    resetFilters();
  };

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys as string[]);
    },
  };

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            {toolTypeIcons[record.toolType as keyof typeof toolTypeIcons]}
            <span style={{ fontWeight: 'bold' }}>{text}</span>
            {record.version !== '1.0.0' && (
              <Tag color="orange">
                v{record.version}
              </Tag>
            )}
          </div>
        </div>
      ),
      sorter: true,
      width: 200
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 250
    },
    {
      title: '类型',
      dataIndex: 'toolType',
      key: 'toolType',
      render: (type: McpToolType) => {
        const typeInfo = mcpToolService.mcpToolTypeMap[type as keyof typeof mcpToolService.mcpToolTypeMap];
        return (
          <Tag color={typeInfo.color} icon={toolTypeIcons[type as keyof typeof toolTypeIcons]}>
            {typeInfo.text}
          </Tag>
        );
      },
      filters: Object.entries(mcpToolService.mcpToolTypeMap).map(([value, { text }]) => ({
        text: text,
        value: value
      })),
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: McpToolStatus) => {
        const statusInfo = mcpToolService.mcpToolStatusMap[status as keyof typeof mcpToolService.mcpToolStatusMap];
        return (
          <Tag color={statusInfo.color}>
            {statusInfo.text}
          </Tag>
        );
      },
      filters: Object.entries(mcpToolService.mcpToolStatusMap).map(([value, { text }]) => ({
        text: text,
        value: value
      })),
      width: 120
    },
    {
      title: '安全等级',
      dataIndex: 'securityLevel',
      key: 'securityLevel',
      render: (level: number) => {
        const levelInfo = mcpToolService.securityLevelMap[level as keyof typeof mcpToolService.securityLevelMap];
        return (
          <Tag color={levelInfo.color}>
            {levelInfo.text}
          </Tag>
        );
      },
      width: 100
    },
    {
      title: '使用统计',
      key: 'usageStats',
      render: (_, record: any) => (
        <div style={{ fontSize: '12px' }}>
          <div>使用: <strong>{record.usageCount}</strong></div>
          <div>成功: <strong>{record.successCount}</strong></div>
          <div>成功率: <strong>{(record.successRate * 100).toFixed(1)}%</strong></div>
          <div>平均耗时: <strong>{record.averageExecutionTimeMs.toFixed(0)}ms</strong></div>
        </div>
      ),
      width: 150
    },
    {
      title: '最后执行',
      dataIndex: 'lastExecutedAt',
      key: 'lastExecutedAt',
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
      sorter: true,
      width: 160
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: any) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button icon={<EyeOutlined />} size="small" onClick={() => handleViewDetail(record)} />
          </Tooltip>
          
          <Tooltip title="执行工具">
            <Button 
              icon={<PlayCircleOutlined />} 
              size="small" 
              onClick={() => handleExecute(record)}
              disabled={!record.isActive || record.status !== McpToolStatus.Configured}
            />
          </Tooltip>
          
          <Tooltip title="测试连接">
            <Button 
              icon={<ThunderboltOutlined />} 
              size="small" 
              onClick={() => handleTestConnection(record)}
            />
          </Tooltip>
          
          <Tooltip title="编辑">
            <Link to={`/mcp-tools/${record.id}/edit`}>
              <Button icon={<EditOutlined />} size="small" />
            </Link>
          </Tooltip>

          <Tooltip title={record.isActive ? '停用' : '激活'}>
            <Button
              icon={record.isActive ? <StopOutlined /> : <CheckCircleOutlined />}
              size="small"
              onClick={() => handleToggleActive(record.id, !record.isActive)}
            />
          </Tooltip>

          <Tooltip title="重置统计">
            <Button
              icon={<ReloadOutlined />}
              size="small"
              onClick={() => handleResetStats(record.id)}
              disabled={record.usageCount === 0}
            />
          </Tooltip>

          {!record.isSystem && (
            <Popconfirm
              title="确定要删除这个工具吗？删除后将无法恢复。"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除">
                <Button icon={<DeleteOutlined />} size="small" danger />
              </Tooltip>
            </Popconfirm>
          )}
        </Space>
      ),
      fixed: 'right',
      width: 240
    }
  ];

  // 计算分页配置
  const paginationConfig = {
    current: Math.floor((filters.skipCount || 0) / (filters.maxResultCount || 10)) + 1,
    pageSize: filters.maxResultCount || 10,
    total: state.totalCount,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100']
  };

  // 错误处理
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        {/* 页面标题和操作栏 */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
              MCP工具管理
            </h1>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Button icon={<BarChartOutlined />} onClick={() => setHistoryVisible(true)}>
                执行历史
              </Button>
              <Link to="/mcp-tools/create">
                <Button type="primary" icon={<PlusOutlined />}>
                  创建工具
                </Button>
              </Link>
            </Space>
          </div>
          
          {/* 搜索和过滤区域 */}
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            <Search
              placeholder="搜索工具名称或描述"
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              allowClear
            />
            
            <Select
              placeholder="类型过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleTypeFilter}
            >
              {Object.entries(mcpToolService.mcpToolTypeMap).map(([value, { text }]) => (
                <Option key={value} value={value as McpToolType}>
                  {text}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="状态过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleStatusFilter}
            >
              {Object.entries(mcpToolService.mcpToolStatusMap).map(([value, { text }]) => (
                <Option key={value} value={value as McpToolStatus}>
                  {text}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="激活状态"
              style={{ width: 120 }}
              allowClear
              onChange={handleActiveFilter}
            >
              <Option value={true}>激活</Option>
              <Option value={false}>停用</Option>
            </Select>

            <Button onClick={handleResetFilters}>
              重置过滤
            </Button>
          </div>
        </div>

        {/* 批量操作工具栏 */}
        {selectedRowKeys.length > 0 && (
          <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
            <Space>
              <span>已选择 {selectedRowKeys.length} 个工具</span>
              <Button size="small" onClick={() => handleBatchSetActive(true)}>
                批量激活
              </Button>
              <Button size="small" onClick={() => handleBatchSetActive(false)}>
                批量停用
              </Button>
              <Popconfirm
                title={`确定要删除选中的 ${selectedRowKeys.length} 个工具吗？`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button size="small" danger>
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          </div>
        )}

        {/* 统计信息 */}
        {statistics && (
          <div style={{ marginBottom: '16px' }}>
            <Row gutter={16}>
              <Col span={6}>
                <Card size="small">
                  <Statistic
                    title="总工具数"
                    value={statistics.totalTools}
                    prefix={<ToolOutlined />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card size="small">
                  <Statistic
                    title="激活工具"
                    value={statistics.activeTools}
                    prefix={<CheckCircleOutlined />}
                    valueStyle={{ color: '#3f8600' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card size="small">
                  <Statistic
                    title="已配置工具"
                    value={statistics.configuredTools}
                    prefix={<SettingOutlined />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card size="small">
                  <Statistic
                    title="平均成功率"
                    value={statistics.averageSuccessRate * 100}
                    suffix="%"
                    prefix={<BarChartOutlined />}
                    valueStyle={{ color: '#722ed1' }}
                  />
                </Card>
              </Col>
            </Row>
          </div>
        )}

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={tools}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          onChange={handleTableChange}
          scroll={{ x: 1600 }}
          bordered
          size="middle"
          rowSelection={rowSelection}
        />
      </Card>

      {/* 工具详情模态框 */}
      <Modal
        title="工具详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedTool && (
          <Descriptions bordered column={1}>
            <Descriptions.Item label="名称">{selectedTool.name}</Descriptions.Item>
            <Descriptions.Item label="描述">{selectedTool.description}</Descriptions.Item>
            <Descriptions.Item label="类型">
              <Tag color={mcpToolService.mcpToolTypeMap[selectedTool.toolType as keyof typeof mcpToolService.mcpToolTypeMap]?.color}>
                {mcpToolService.mcpToolTypeMap[selectedTool.toolType as keyof typeof mcpToolService.mcpToolTypeMap]?.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={mcpToolService.mcpToolStatusMap[selectedTool.status as keyof typeof mcpToolService.mcpToolStatusMap]?.color}>
                {mcpToolService.mcpToolStatusMap[selectedTool.status as keyof typeof mcpToolService.mcpToolStatusMap]?.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="版本">{selectedTool.version}</Descriptions.Item>
            <Descriptions.Item label="命令">{selectedTool.command}</Descriptions.Item>
            <Descriptions.Item label="超时时间">{selectedTool.timeoutSeconds}秒</Descriptions.Item>
            <Descriptions.Item label="安全等级">
              <Tag color={mcpToolService.securityLevelMap[selectedTool.securityLevel as keyof typeof mcpToolService.securityLevelMap]?.color}>
                {mcpToolService.securityLevelMap[selectedTool.securityLevel as keyof typeof mcpToolService.securityLevelMap]?.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="参数">
              {selectedTool.parameters && selectedTool.parameters.length > 0 ? (
                <div>
                  {selectedTool.parameters.map((param: McpToolParameter, index: number) => (
                    <Tag key={index} color="blue">
                      {param.name} ({param.type}) {param.isRequired ? '*' : ''}
                    </Tag>
                  ))}
                </div>
              ) : (
                <span>无参数</span>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="标签">
              <Space size="small" wrap>
                {selectedTool.tags?.split(',').map((tag: string, index: number) => (
                  <Tag key={index} color="purple">
                    {tag.trim()}
                  </Tag>
                ))}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="作者">{selectedTool.author || '-'}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{new Date(selectedTool.creationTime).toLocaleString()}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 执行工具模态框 */}
      <Modal
        title="执行工具"
        open={executeVisible}
        onOk={handleExecuteTool}
        onCancel={() => setExecuteVisible(false)}
        width={800}
      >
        {selectedTool && (
          <Form form={executeForm} layout="vertical">
            <Form.Item label="工具名称">
              <Input value={selectedTool.name} disabled />
            </Form.Item>
            
            {selectedTool.parameters?.map((param: McpToolParameter) => (
              <Form.Item
                key={param.name}
                name={['parameters', param.name]}
                label={`${param.name} (${param.type})${param.isRequired ? ' *' : ''}`}
                rules={param.isRequired ? [{ required: true, message: `请输入${param.name}` }] : undefined}
              >
                {param.type === 'boolean' ? (
                  <Switch />
                ) : param.type === 'number' ? (
                  <Input type="number" placeholder={param.description} />
                ) : (
                  <Input placeholder={param.description} />
                )}
              </Form.Item>
            ))}

            {executionResult && (
              <Form.Item label="执行结果">
                <Alert
                  message={executionResult.isSuccess ? "执行成功" : "执行失败"}
                  description={
                    <div>
                      {executionResult.isSuccess ? (
                        <pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>
                          {JSON.stringify(executionResult.data, null, 2)}
                        </pre>
                      ) : (
                        <div style={{ color: '#ff4d4f' }}>
                          错误: {executionResult.errorMessage}
                        </div>
                      )}
                      <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
                        执行时间: {executionResult.executionTimeMs}ms
                      </div>
                    </div>
                  }
                  type={executionResult.isSuccess ? "success" : "error"}
                  showIcon
                />
              </Form.Item>
            )}
          </Form>
        )}
      </Modal>

      {/* 执行历史模态框 */}
      <Modal
        title="执行历史"
        open={historyVisible}
        onCancel={() => setHistoryVisible(false)}
        footer={[
          <Button key="clear" onClick={clearExecutionHistory}>
            清除历史
          </Button>,
          <Button key="close" type="primary" onClick={() => setHistoryVisible(false)}>
            关闭
          </Button>
        ]}
        width={1000}
      >
        <Table
          dataSource={executionHistory}
          rowKey="executionId"
          pagination={{ pageSize: 10 }}
          columns={[
            {
              title: '执行时间',
              dataIndex: 'executionTime',
              render: (text: string) => new Date(text).toLocaleString(),
              width: 180
            },
            {
              title: '工具ID',
              dataIndex: 'toolId',
              render: (id: string) => id.substring(0, 8) + '...',
              width: 120
            },
            {
              title: '执行结果',
              dataIndex: 'isSuccess',
              render: (isSuccess: boolean) => (
                <Tag color={isSuccess ? 'success' : 'error'}>
                  {isSuccess ? '成功' : '失败'}
                </Tag>
              ),
              width: 100
            },
            {
              title: '执行时间',
              dataIndex: 'executionTimeMs',
              render: (time: number) => `${time}ms`,
              width: 100
            },
            {
              title: '错误信息',
              dataIndex: 'errorMessage',
              ellipsis: true,
              width: 200
            },
            {
              title: '操作',
              key: 'actions',
              render: (_, record: any) => (
                <Button
                  size="small"
                  icon={<EyeOutlined />}
                  onClick={() => {
                    setSelectedTool(tools.find(t => t.id === record.toolId));
                    setExecuteVisible(true);
                  }}
                >
                  查看详情
                </Button>
              ),
              width: 100
            }
          ]}
        />
      </Modal>
    </div>
  );
};

export default McpToolList;